package org.quipu.client;

import com.google.gwt.i18n.client.NumberFormat;
import org.quipu.AppException;

public final class StringUtils {

    private StringUtils() {
    }

    /**
     * This method returns an String where the ingested value is repeated n times.
     *
     * @param s Input String
     * @param n Number of times is repeated
     * @return new String with the parameter repeated
     */
    public static String repeat(String s, int n) {
        if (s == null) {
            return null;
        }
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(s);
        }
        return sb.toString();
    }

    public static Double parseSum(String strSum) throws AppException {
        Double sum = 0.0;
        if(strSum != null) {
            strSum = strSum.replace(',', '.');
            try {
                sum = Double.valueOf(strSum);
            } catch(NumberFormatException ex) {
                throw new AppException(ex);
            }
        } else {
            throw new AppException("sum is null");
        }
        return sum;
    }

    public static String doubleToString(Double value) {
        String strSum;
        if(value == null || value == 0.0) {
            strSum = "0";
        } else {
            strSum = String.valueOf(value);
        }
        return strSum;
    }

    public static String formatSum(Double sum, boolean grouping) {
        String strSum;
        if(sum == null || sum == 0.0) {
            strSum = "0";
        } else {
            String format = grouping? "#,###,###,##0.00": "#########0.00";
            strSum = NumberFormat.getFormat(format).format(sum);
        }
        return strSum;
    }

    public static String formatRate(Double sum) {
        String strSum;
        if(sum == null || sum == 0.0) {
            strSum = "0";
        } else {
            strSum = NumberFormat.getFormat("#,###,###,##0.00000").format(sum);
        }
        return strSum;
    }
}
